#!/usr/bin/env python2
import pickle
import os
HOME = os.getenv('USERPROFILE') or os.getenv('HOME')

def difference(list1, list2):
    k1, k2 = list1[0].keys()
    biglist1_indexed = {}
    matches = []
    #
    for item in list1:
        biglist1_indexed[(item[k1], item[k2])] = item
    #
    for item in list2:
        if (item[k1], item[k2]) not in biglist1_indexed:
            matches.append(item)
    return matches


def returnsOriginalData(list1, contentType, MODULE, tvshowName=None):
    #'list' is the list that is sent to the function
    #'contentType' is the string that tells us what type of content it is: movie,tvshow,tvshowName
    #'tvshowName' is set by default to None, it we are getting a episode list for a tvshowName, it will have a string
    #
    #we need to check if the directory for the pickle file exists, if it does not exist, make it,
    PATH = HOME+'/.'+'getmovies/cache/'+MODULE+'/'
    if os.path.isdir(PATH):
        pass
    else:
        os.makedirs(PATH)
    #first we check if the pickle for the contentType exists.
    #for that we build a path string.
    if tvshowName:
        PATH += contentType+tvshowName
    else:
        PATH += contentType
    #we have the path now and need to check if it actually exists, if it does, open it, 
    # save difference in list3
    # append list3 to list2 and pickle it, 
    #return list3
    #if not, return the list as is
    if os.path.isfile(PATH):
        pickleFile=(open(PATH, 'rb'))
        list2 = pickle.load(pickleFile)
        pickleFile.close()
        list3 = difference(list1, list2)
        list2 += list3
        output = open(PATH, 'wb')
        pickle.dump(list2, output)
        output.close()
        return list3
    else:
        output = open(PATH, 'wb')
        pickle.dump(list1, output)
        output.close()
        return list1